package com.huang.other;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.huang.bo.AreaTaskBo;
import com.huang.entity.AreaTaskDetail;
import com.huang.service.AreaTaskDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * author  : struggle
 * version : 1.0.0
 */
public class AreaTaskListener extends AnalysisEventListener<AreaTaskBo> {
    private final AreaTaskDetailService areaTaskDetailService;
    private final Long taskId;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final int BATCH_COUNT = 50;

    //由于每次读都是新new UserInfoDataListener的，所以这个list不会存在线程安全问题
    List<AreaTaskDetail> list = new ArrayList<>();

    public AreaTaskListener(Long taskId, AreaTaskDetailService areaTaskDetailService) {
        this.areaTaskDetailService = areaTaskDetailService;
        this.taskId = taskId;
    }

    @Override
    public void invoke(AreaTaskBo data, AnalysisContext context) {
        AreaTaskDetail areaTaskDetail = new AreaTaskDetail();
        areaTaskDetail.setTaskId(taskId);
        areaTaskDetail.setKeywords(data.getKeywords());
        areaTaskDetail.setUrl(data.getUrl());
        list.add(areaTaskDetail);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        logger.info("所有数据解析完成！");
    }
    private void saveData() {
        logger.info("{}条数据，开始存储数据库！", list.size());
//        保存数据
        areaTaskDetailService.saveBatch(list);
        logger.info("存储数据库成功！");
    }

}
